package com.aliyun.heiyu.powermaster.server.rbac.utils;

import com.alibaba.fastjson.JSONArray;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.SystemDefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author czx
 * @Description
 * @Version 2019-01-01 22:13
 */
public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    public static JSONObject postRequest(String json, String host) {
        JSONObject jsonobj = null;
        //创建http连接调用第三方接口
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(host);
            if (json != null) {
                StringEntity requestEntity = new StringEntity(json);
                requestEntity.setContentEncoding("UTF-8");
                requestEntity.setContentType("application/json");
                //使用post请求将json数据作为请求体
                httpPost.setEntity(requestEntity);
            }
            //发送请求，处理响应
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                //判断响应码，看是否请求成功
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    return null;
                }
                jsonobj = new JSONObject(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            logger.error(e.getMessage(), e);
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return jsonobj;
    }
    public static JSONObject postRequest(String json, Map<String, String> headMap, String host) {
        JSONObject jsonobj = null;
        //创建http连接调用第三方接口
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(host);
            if (json != null) {
                StringEntity requestEntity = new StringEntity(json);
                requestEntity.setContentEncoding("UTF-8");
                requestEntity.setContentType("application/json");
                //使用post请求将json数据作为请求体
                httpPost.addHeader("record_time",headMap.get("record_time"));
                httpPost.setEntity(requestEntity);
            }
            //发送请求，处理响应
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                //判断响应码，看是否请求成功
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    return null;
                }
                jsonobj = new JSONObject(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            logger.error(e.getMessage(), e);
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return jsonobj;
    }

    public static String doGet(String url) {                            // 无参数get请求
        return doGet(url, null);
    }

    public static String doGet(String url, Map<String, String> param) {    // 带参数get请求
        CloseableHttpClient httpClient = HttpClients.createDefault();    // 创建一个默认可关闭的Httpclient 对象
        String resultMsg = "";                                            // 设置返回值
        CloseableHttpResponse response = null;                            // 定义HttpResponse 对象
        try {
            URIBuilder builder = new URIBuilder(url);                    // 创建URI,可以设置host，设置参数等
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);                    // 创建http GET请求
            response = httpClient.execute(httpGet);                        // 执行请求
            if (response.getStatusLine().getStatusCode() == 200) {        // 判断返回状态为200则给返回值赋值
                resultMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {                                                        // 不要忘记关闭
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMsg;
    }

    public static String doPost(String url) {                            // 无参数post请求
        return doPost(url, null,null);
    }

    public static String doPost(String url, Map<String, String> param,Map<String,String> header) {// 带参数post请求
        CloseableHttpClient httpClient = HttpClients.createDefault();    // 创建一个默认可关闭的Httpclient 对象

        CloseableHttpResponse response = null;
        String resultMsg = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            //设置post请求的请求头
            if(header==null || header.equals("") || header.size()<=0){
            }else{
                for(Map.Entry<String, String> vo : header.entrySet()){
                    if(vo.getValue()==null || vo.getValue().equals("")){
                        continue;
                    }
                    httpPost.setHeader(vo.getKey(),vo.getValue());
                }
            }


            if (param != null) {                                        // 创建参数列表
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);// 模拟表单
                httpPost.setEntity(entity);
            }
            response = httpClient.execute(httpPost);                    // 执行http请求
            if (response.getStatusLine().getStatusCode() == 200) {
                resultMsg = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMsg;
    }

    public static String doPostJson(String url, String json,Map<String,String> header) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPost httpPost = new HttpPost(url);   //设置post请求的请求头
            if(header==null || header.equals("") || header.size()<=0){
            }else{
                for(Map.Entry<String, String> vo : header.entrySet()){
                    if(vo.getValue()==null || vo.getValue().equals("")){
                        continue;
                    }
                    httpPost.setHeader(vo.getKey(),vo.getValue());
                }
            }
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);     //指定传输参数为json
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 发送get请求，参数为json
     * @param url
     * @param param
     * @param encoding
     * @return
     * @throws Exception
     */
    public static String sendJsonByGetReq(String url, String param, String encoding) throws Exception {
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
        HttpEntity httpEntity = new StringEntity(param, ContentType.APPLICATION_JSON);
        httpGetWithEntity.setEntity(httpEntity);
        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpGetWithEntity);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        //释放链接
        response.close();
        return body;
    }
}
